package com.cuit.handler;


import com.cuit.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.impl.FileSizeLimitExceededException;
import org.apache.tomcat.util.http.fileupload.impl.SizeLimitExceededException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;

// 对加了@Conttroller注解的方法进行拦截处理，AOP实现
@ControllerAdvice
@Slf4j
public class AllExceptionHandler {

    // 进行异常处理，处理Exception.class的异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result doException(Exception e){

        e.printStackTrace();
        return Result.fail(998,"系统出错了,请联系管理员,详细错误如下:" + e.toString());
    }
//    private static int GENERIC_SERVER_ERROR_CODE = 2000;
//    private static String GENERIC_SERVER_ERROR_MESSAGE = "服务器忙，请稍后再试";

//    @ExceptionHandler
//    @ResponseBody
//    public Result handle(HttpServletRequest req, HandlerMethod method, Exception ex) {
//        if (ex instanceof BusinessException) {
//            BusinessException exception = (BusinessException) ex;
//            log.warn(String.format("访问 %s -> %s 出现业务异常！", req.getRequestURI(), method.toString()), ex);
//            return Result.fail(677,"业务异常");
//        } else if (ex instanceof RuntimeException){
//            log.error(String.format("访问 %s -> %s 出现运行时异常！", req.getRequestURI(), method.toString()), ex);
//            return Result.fail(678,"运行时异常");
//        }
//        else {
//            log.error(String.format("访问 %s -> %s 出现系统异常！", req.getRequestURI(), method.toString()), ex);
//            return Result.fail(679,"系统异常");
//        }
//    }

    @ExceptionHandler(MultipartException.class)
    @ResponseBody
    public Result exception(MaxUploadSizeExceededException e){
        if (e.getCause().getCause() instanceof FileSizeLimitExceededException){//单个文件大小超出限制抛出的异常
            log.error("message异常信息为=========》"+e.getMessage());
            log.error("cause异常信息为=========》"+e.getCause().getCause());
            return Result.fail(444,"单个上传文件大小不能超过50MB");
        }else if (e.getCause().getCause() instanceof SizeLimitExceededException){//总文件大小超出限制抛出的异常
            log.error("message异常信息为=========》"+e.getMessage());
            log.error("cause异常信息为=========》"+e.getCause().getCause());
            return Result.fail(445,"总上传文件大小不能超过500MB");
        }else {
            return Result.fail(446,"文件上传异常");
        }
    }

}
